package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.client.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.mapper.XcUserRoleMapper;
import com.xuecheng.ucenter.model.dto.RegisterDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.model.po.XcUserRole;
import com.xuecheng.ucenter.service.RegisterService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class RegisterServiceImpl implements RegisterService {


    @Autowired
    CheckCodeClient client;
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    XcUserRoleMapper xcUserRoleMapper;


    @Override
    public void register(RegisterDto registerDto) {
        String checkcodekey = registerDto.getCheckcodekey();
        String email = registerDto.getEmail();
        String checkcode = registerDto.getCheckcode();

        //1.对验证码进行校验
        Boolean verify = client.verify(email, checkcode);
        if (!verify) {
            throw new RuntimeException("验证码不正确");
        }

        //2.对输入的两次密码进行校验
        String password = registerDto.getPassword();
        String confirmpwd = registerDto.getConfirmpwd();
        if (!password.equals(confirmpwd)) {
            throw new RuntimeException("输入的两次密码不一致");
        }

        //3.判断用户是否存在
        LambdaQueryWrapper<XcUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(XcUser::getEmail, email);
        XcUser xcUser = xcUserMapper.selectOne(lambdaQueryWrapper);
        if (xcUser != null) {
            throw new RuntimeException("一个邮箱只能注册一个账号");
        }

        //4.添加用户
        XcUser user = new XcUser();
        BeanUtils.copyProperties(registerDto, user);
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        String id = UUID.randomUUID().toString();
        user.setId(id);
        user.setName(registerDto.getUsername());
        user.setSex("1");
        user.setUtype("101001");  // 学生类型
        user.setCreateTime(LocalDateTime.now());
        int insert = xcUserMapper.insert(user);
        if (insert <= 0) {
            throw  new RuntimeException("新增用户失败");
        }

        //5.新增用户权限--设置权限为学生
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setId(id);
        xcUserRole.setUserId(id);
        xcUserRole.setRoleId("17");
        xcUserRole.setCreateTime(LocalDateTime.now());
        int insert1 = xcUserRoleMapper.insert(xcUserRole);
        if (insert1<=0){
            throw new RuntimeException("新增用户角色信息失败");
        }
    }
}
